/**
   nc_writer.cpp - Created by Timothy Morey on 2/8/2012.

   This file contains the implementation for the NCWriter object.
 */

#include <netcdf.h>
#include <stdio.h>

#include "nc_writer.h"

#define NETCDF_CALL(x)                                                       \
  {                                                                          \
    int err = x;                                                             \
    if(err != NC_NOERR)                                                      \
      printf("NetCDF Error on call \"%s\" \n\t%s\n\tLine: %d, File: %s\n",   \
	     #x, nc_strerror(err), __LINE__, __FILE__);                      \
  }

NCWriter::NCWriter(const char* filename, unsigned short width, unsigned short height)
  : _NCID(-1),
    _ColDimID(-1),
    _RowDimID(-1),
    _StepDimID(-1),
    _ForestWidth(width),
    _ForestHeight(height)
{
  NETCDF_CALL( nc_create(filename, NC_NETCDF4, &_NCID) );

  NETCDF_CALL( nc_def_dim(_NCID, "column", width, &_ColDimID) );
  NETCDF_CALL( nc_def_dim(_NCID, "row", height, &_RowDimID) );
  NETCDF_CALL( nc_def_dim(_NCID, "step", NC_UNLIMITED, &_StepDimID) );

  int dimids[3] = { _StepDimID, _RowDimID, _ColDimID };
  NETCDF_CALL( nc_def_var(_NCID, "value", NC_UINT, 3, dimids, &_ValueVarID) );

  NETCDF_CALL( nc_enddef(_NCID) );
}

NCWriter::~NCWriter()
{
  if(_NCID != -1)
  {
    NETCDF_CALL( nc_close(_NCID) );
    _NCID = -1;
  }
}

void NCWriter::WriteStep(unsigned int* forest, unsigned int stepNum)
{
  size_t count[3] = { 1, _ForestHeight, _ForestWidth };
  size_t start[3] = { stepNum, 0, 0 };
  NETCDF_CALL( nc_put_vara_uint(_NCID, _ValueVarID, start, count, forest) );
}

